<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, computed } from 'vue';
import {
  getCurrentInstance,
  showToast,
  hideLoading,
  showLoading,
  usePullDownRefresh,
  stopPullDownRefresh,
  useShareAppMessage,
  requestPayment
} from '@tarojs/taro';
import { useRouterPush } from '@/composables';
import { useNurseGoods } from '@/service';
import { useNurseOrders } from '@/service';
import { useImage } from '@/hooks';
import { storeToRefs } from 'pinia';
import { useAuthStore, useGoodsStore, useTempShopStore } from '@/store';
const { toOrders } = useRouterPush();
import part1 from './part1.vue';
import part2 from './part2.vue';
import part3 from './part3.vue';
// import part4 from './part4.vue';
import part5 from './part5.vue';
import know from './know.vue';
import partGoods from './part-goods.vue';
import care from '@/components/basic-comm/care.vue';
import pic from '@/assets/ico/info.jpg';
import LoginStatusCheck from '@/components/login-status-check/index.vue';
const part1Ref = ref();
const part2Ref = ref();
const part3Ref = ref();
const partGoodsRef = ref();
const loginStatusRef = ref();
const { nurseUser } = storeToRefs(useAuthStore());

console.log('nurseUser 😂😂', nurseUser.value);

const { getGoodsDetail } = useNurseGoods();
const { toHelp, toGoodsPay, toMine } = useRouterPush();
const { addByWeChat, payByWeChat, queryByWeChat, closeByWeChat, getFeeControl } = useNurseOrders();
const goodsStore= useGoodsStore();
const tempShopStore = useTempShopStore();

// 计算总合计（包含商品费用和临时商店费用）
const grandTotal = computed(() => {
  return goodsStore.totalFee + tempShopStore.getTotalPrice;
});

const {
  router: {
    params: { id, pname, unit, nurseType, goods_type, nurseTypeText }
  }
}: any = getCurrentInstance();

const {
  router: { $taroPath }
}: any = getCurrentInstance();



useShareAppMessage(res => {
  return {
    title: pname,
    path: $taroPath, // 路由路径
    imageUrl: data.value?.goods?.imagePath
  };
});

definePageConfig({
  navigationBarTitleText: pname,
  enablePullDownRefresh: true,
  enableShareAppMessage: true
});

// Taro.setNavigationBarTitle({
//     title: type == 1 ? '申请开票' : '发票详情'
// })

getData();

usePullDownRefresh(() => {
  getData();
  stopPullDownRefresh();
});

const data = ref();

const list = ref([]);

const index = ref();

function getItem(index: number) {
  const item: any = list.value[index];
  let images = item?.pic?.split(',');
  images = images.map((el: string) => {
    return useImage(el);
  });
  let descriptionPic = item?.descriptionPic?.split(',');
  descriptionPic = descriptionPic.map((el: string) => {
    return useImage(el);
  });
  const skuList = list.value.map((el: any, i) => {
    return { index: i, name: el.goodsName, id: el.id, active: i == index, disable: false };
  });
  return {
    id: item.id,
    images,
    price: item.price,
    descriptionPic,
    sku: [
      {
        name: '类型规格',
        list: [...skuList]
      }
    ],
    goods: {
      skuId: item.id,
      price: item.price,
      name: item.goodsName,
      imagePath: useImage(item.tpic)
    }
  };
}

async function getData() {
  showLoading({ title: '正在请求数据...' });

  const { error, success } = await getGoodsDetail({ goods_id: id, goods_type });

  if (!error && success?.length > 0) {
    list.value = success;
    goodsStore.init(success?.[0]?.standardCode || 1);
    console.log('list? 😂😂?', list?.value);
    goodsStore.duration = list.value?.[0]?.duration || 60;
    goodsStore.price = list.value?.[0]?.price || 0;
    index.value = 0;
    data.value = getItem(index.value);
    console.log('data 888 😂😂', data.value);
  }
  hideLoading();
}

const visible = ref(false);

const selectSku = (ss: { sku: any }) => {
  const { sku } = ss;
  data.value = getItem(sku.index);
};

const val = ref(1);

const num = ref(1);

const onChange = (index: number) => {
  val.value = index + 1;
};

function toPay() {
  if (!nurseUser.value.phone) {
    showToast({
      title: '请先完善用户信息！',
      icon: 'none',
      duration: 1500
    });
    setTimeout(() => {
      toMine(1);
    }, 1500);
    return;
  }
  toGoodsPay({
    goodsId: data.value?.goods.skuId,
    pid: id,
    pname,
    nurseType,
    name: data.value?.goods.name,
    num: num.value,
    pic: data.value?.goods.imagePath,
    price: data.value?.goods.price,
    unit,
    nurseTypeText
  });
}

const agree = ref(false);
// let timers = 0
// const totalPrice = ref(0)
onMounted(() => {
  console.log('onMounted 😂😂');
  // timers = setInterval(() => {
  //   totalPrice.value = (part1Ref.value.getPrice() + part2Ref.value.getPrice()) * part3Ref.value.getTimes();
  //   preCharge.value = totalPrice.value;
  // }, 1600)
});
onBeforeUnmount(() => {
  // clearInterval(timers)
  
})

async function actionPay(){
  // 检查登录状态
  if (!loginStatusRef.value?.requireLogin?.({
    title: '提示',
    content: '请先登录才能购买商品'
  })) {
    return
  }
  
  if(!goodsStore.beginDate || !goodsStore.endDate){
    showToast({
      title: '请选择期望上门时间',
      icon: 'none',
      duration: 2000
    })
    return
  }

  
  //如果goodsStore.beginDate 和现在距离不足3小时，则提示不能下单
  const beginDate = new Date(goodsStore.beginDate);
  const now = new Date();
  const diffTime = beginDate.getTime() - now.getTime();
  const diffHours = Math.ceil(diffTime / (1000 * 60 * 60));
  console.log('diffHours 😂😂', diffHours);
  if(diffHours < 3){
    showToast({
      title: '请选择大于3小时后的时间',
      icon: 'none',
      duration: 2000
    })
    return
  }

  const goodsName = data.value?.goods.name
  // const {beginDate, endDate} = part2Ref.value.getTimestr()
  const param: any = {
    // name: "画画15677889900",
    address: "广西壮族自治区南宁市青秀区玩儿",
    hospital: nurseUser.value.defaultHospitalName || "广西医科大学第二附属医院护理科护理001",
    hospitalId: nurseUser.value.defaultHospital || "1",
    nurseUserOrdersDetails: [
      {
        // price: data.value?.goods.price,//"0.01",
        price: goodsStore.sku.cur?.price || 0,
        unit: "小时",
        num: goodsStore.times,
        goodsName: goodsName,// "生命体征测量",
        goodsId: data.value?.goods.skuId, //"1914524002470748161",
        pname: pname, //"生命体征测量",
        pid: id, //"1914523872334077953",

      }
    ],
    specialDetails: [],
    specialAmt: "",
    // beginDate: "2025-06-17 00:00:00",
    // endDate: "2025-06-17 23:59:59",
    remark: goodsStore.remark,
    addrId: nurseUser.value.nurseUserAddrList[0].id, // "1926457126490406914",
    familyId: goodsStore.family.id || -1, //"1926457126146473985",  
    userId: nurseUser.value.id, //"1923575925480013825"
    orderText: data.value?.goods.name || "[生命体征测量]-[生命体征测量]",
    nurseType: nurseType, // "2",
    // end: 0,
    nightId: goodsStore.night.choose ? goodsStore.night.options[0]?.id : -1,//夜间费ID
    isGoHome: goodsStore.pickup.choose ? "1" : "0",
    ispickup: goodsStore.pickup.choose ? "1" : "0",
    urgentId: goodsStore.urgent.cur?.id || -1,//加急ID
    urgentName: goodsStore.urgent.cur?.name || "不指定",
    urgentFee: goodsStore.urgentFree,
    expertId: goodsStore.expert.cur?.id || -1,//专家ID
    expertName: goodsStore.expert.cur?.name || "不指定",
    expertFee: goodsStore.expertTotalFee,
    distanceId: goodsStore.distance.id,//远程费ID
    distanceName: "远程费",
    distanceFee: goodsStore.distanceTotalFee,
    distanceOldFee: goodsStore.distanceFee,
    expertOldFee: goodsStore.expertFree,
    totalPrice: grandTotal.value,

    expertNum: 1,
    distanceNum: 1,
  }

  if(tempShopStore.hasGoods){
    const medicationOrderDetailS: any[] = []
    tempShopStore.goodsList.forEach(item => {
      medicationOrderDetailS.push({
        goodsId: item.id,
        num: parseInt(tempShopStore.numMap[item.id]),
        goodsName: item.typeName,
      })
    })
    param.medicationOrderDetails = medicationOrderDetailS
  }
  const all = {
    ...param,
      beginDate: goodsStore.beginDate,
      endDate: goodsStore.endDate,
      // beginDate: `${formData.value.beginDate} 00:00:00`,
      // endDate: `${formData.value.endDate} 23:59:59`,
      orderText: `[${nurseTypeText}]${pname !== goodsName ? `[${pname}]` : ''}-[${goodsName}]`
  }
   const { error, success } = await addByWeChat({
      ...all,
      orderJson: JSON.stringify(all)
  });

  console.log("error", error)
  console.log("success", success)

  if (!error && success) {
      showToast({
          title: '下单成功',
          icon: 'success',
          duration: 2000
      });
      // payInfo = success;
      const { timestamp, noncestr, package: packAge, sign } = success;

      await requestPayment({
        timeStamp: timestamp,
        nonceStr: noncestr,
        package: packAge,
        paySign: sign,
        signType: 'RSA',
        fail: () => {
            // if (pay !== '1') toOrders();
            showToast({
                title: '支付失败',
                icon: 'none',
                duration: 2000
            })
        },
        complete() {
            hideLoading();
            // loading.value = false;
        },
        success: res => {
            if (res.errMsg == 'requestPayment:ok') {
                showToast({
                    title: '支付成功！',
                    icon: 'success',
                    duration: 1500
                });
                setTimeout(() => {
                    toOrders();
                }, 1500);
            }
        }
    });
  }
  else{
    showToast({
      title: error?.message || "下单失败",
      icon: 'none',
      duration: 2000
    })
  }
}

const preCharge = ref(0)

</script>
<template>
  <basic-layout>
    <!-- <custom-navbar :title="pname" showLeft /> -->
    <!-- 登录状态检查组件 -->
    <LoginStatusCheck ref="loginStatusRef" />
    
    <view class="w-375px text-primary flex-col-center">
      <view class="w-360px flex-col-center m-b-15">
        <view class="bg-#fff mt-2 b-rounded-3 shadow w-full">
          <nut-swiper :auto-play="0" :loop="false" class="b-rounded-t-3" :init-page="val" @change="onChange">
            <nut-swiper-item v-for="(item, index) in data?.images" :key="index" class="swiper_item">
              <image :src="item" alt="" class="swiper_img" draggable="false" mode="aspectFill" />
            </nut-swiper-item>
            <template #page>
              <view class="swiper-pagination">{{ val }}/{{ data?.images?.length }}</view>
            </template>
          </nut-swiper>

          <view class="m-2 flex my-2 justify-between items-start">
            <view class="flex-1 text-24rpx">{{ pname }}</view>
            <view class="font-bold text-24rpx text-#e11d48">技术服务费: ¥{{ goodsStore.price || 0 }}</view>
          </view>
        </view>


        <part1 :obj="data" ref="part1Ref" />
        <part2 ref="part2Ref" />
        <part3 ref="part3Ref" :preCharge="preCharge" />
       
        <image class="w-full my-2" :src="pic" mode="widthFix" />
        <!-- <view v-html="list[0]?.description"></view> -->
        <rich-text :nodes="list[0]?.description" />

        <view class="bg-#fff my-2 b-rounded-3 shadow w-full flex-col-center">
          <view class="w-350px flex-col-center m-b-2">
            <view class="font-bold ml-2 m-t-2 text-lg">服务详情</view>
            <rich-text :nodes="list[0]?.descriptionPic" class="w-full rchs" />
            <!-- <image v-for="item in data?.descriptionPic" class="swiper_img m-t-2" mode="widthFix" draggable="false"
              alt="" :src="item" /> -->
          </view>
        </view>

        <partGoods ref="partGoodsRef" :preCharge="preCharge" />

   
        <part5 v-model="agree" />
        <!-- <part4 :desc="list[0]?.description" /> -->
        <care />
        <know v-model="agree" />

      </view>
      <view class="w-375px bg-white pos-fixed pos-bottom-0px pos-left-0 flex-col-center z-3">
        <view class="box-border px-4 py-2 flex w-full bg-[#f0f0f0]">
          <text class="text-sm">合计：</text>
          <text class="text-red text-sm ml-auto">¥{{ grandTotal }}</text>
        </view>
        <view class="w-360px m-y-2 flex-center justify-around">
          <view class="w-40px h-40px flex-col-center">
            <view class="i-local-share-bold w-24px h-24px" />
            <view class="text-xs">分享</view>
          </view>
          <view class="w-40px h-40px flex-col-center" @click="toHelp">
            <view class="i-local-customer w-24px h-24px" />
            <view class="text-xs">客服</view>
          </view>
          <nut-button :disabled="!agree" class="important:w-150px font-bold text-lg"
            :type="agree ? 'primary' : 'default'" @click="actionPay">
            立即购买
          </nut-button>
        </view>
      </view>

      <nut-sku v-model:visible="visible" :sku="data?.sku" :goods="data?.goods" @selectSku="selectSku"
        @clickBtnOperate="toPay">
        <template #sku-stepper class="w-360px">
          <view class="w-360px flex justify-between items-center">
            <view class="text-13px text-black font-bold">购买数量:</view>
            <nut-input-number v-model="num" class="m-r-20" :button-size="30" :input-width="50" />
          </view>
        </template>
      </nut-sku>
    </view>
  </basic-layout>
</template>

<style lang="scss">
.rchs{
  img{
    width: 100% !important;
    height: auto !important;
  }
}
.swiper_item {
  height: 200px;
}

.swiper_img {
  height: 100%;
  width: 100%;
  border-radius: 24rpx;
  object-fit: cover;
}

.swiper-pagination {
  position: absolute;
  bottom: 0;
  right: 0;
  width: 46px;
  height: 22px;
  background: rgba(0, 0, 0, 0.33);
  border-radius: 22px;
  text-align: center;
  color: #fff;
  font-size: 14px;
}
</style>
